package com.library.controller;

import com.library.entity.Book;
import com.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping("/list")
    public String listBooks(
        @RequestParam(defaultValue = "1") int pageNum,
        @RequestParam(defaultValue = "8") int pageSize,
        HttpSession session) {
    
        // 计算起始位置
        int offset = (pageNum - 1) * pageSize;
    
        // 获取分页数据和总记录数
        List<Book> books = bookService.getBooksByPage(offset, pageSize);
        int totalCount = bookService.getTotalCount();
    
        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
    
        // 存入session
        session.setAttribute("books", books);
        session.setAttribute("currentPage", pageNum);
        session.setAttribute("totalPages", totalPages);
    
        return "index";
    }

    // 例如修改addBook方法
    @PostMapping("/add")
    public String addBook(@ModelAttribute Book book, BindingResult result, HttpSession session) {
        if(result.hasErrors()) {
            result.getAllErrors().forEach(error -> System.out.println(error));
            return "redirect:/index.jsp?error=true";
        }
        bookService.addBook(book);
        
        // 获取当前页码并重定向
        int currentPage = session.getAttribute("currentPage") != null ? 
            (int) session.getAttribute("currentPage") : 1;
        return "redirect:/book/list?pageNum=" + currentPage;
    }

    @PostMapping("/update")
    public String updateBook(@ModelAttribute Book book) {
        bookService.updateBook(book);
        return "redirect:/book/list";
    }

    @GetMapping("/delete")
    public String deleteBook(@RequestParam int id) {
        bookService.deleteBook(id);
        return "redirect:/book/list";
    }

    @GetMapping("/get")
    @ResponseBody
    public Book getBook(@RequestParam int id) {
        return bookService.getBookById(id);
    }
}